//
//  ThingsInfoViewController.m
//  糗事百科
//
//  Created by lanou on 16/5/28.
//  Copyright © 2016年 奚超明. All rights reserved.
//

#import "ThingsInfoViewController.h"
#import "RequestManager.h"
#import "ThingsListModel.h"
#import "InfoTableViewCell.h"
#import "ThingstextTableViewCell.h"
#import "ThingsimageTableViewCell.h"
#import "ThingsvideoTableViewCell.h"
#import "VideoPlayer.h"
#import <ShareSDKUI/ShareSDK+SSUI.h>
@interface ThingsInfoViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,copy)NSString *hotString;
@property (nonatomic,copy)NSString *auhorString;
@property (nonatomic,copy)NSString *listString;
@property (nonatomic,strong)NSMutableArray *hotarry;
@property (nonatomic,strong)NSMutableArray *listarry;
@property (nonatomic,assign) NSInteger page;
@property (nonatomic, strong) VideoPlayer *player;
@end

@implementation ThingsInfoViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%@",_infoima);
    _hotarry = [NSMutableArray array];
    _listarry = [NSMutableArray array];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight) style:UITableViewStyleGrouped];
    [self.tableView registerNib:[UINib nibWithNibName:@"InfoTableViewCell" bundle:nil] forCellReuseIdentifier:@"infocell"];
    _hotString = [NSString stringWithFormat:@"%@%@/hot/comments",kinfourl,[NSString stringWithFormat:@"%@",_infoid]];
    _listString = [NSString stringWithFormat:@"%@%@/latest/comments",kinfourl,[NSString stringWithFormat:@"%@",_infoid]];
    _auhorString = [NSString stringWithFormat:@"%@%@/comment/author",kinfourl,[NSString stringWithFormat:@"%@",_infoid]];
       _page = 1;
    [self requestDataWithType:@"hot"];
    [self requestDataWithType:@"list"];
    
    //表头视图
    if ([_type isEqualToString:@"word"])
    {
        ThingstextTableViewCell *textview = [[[NSBundle mainBundle]loadNibNamed:@"ThingstextTableViewCell" owner:nil options:nil] objectAtIndex:0];
        [textview.texticon sd_setImageWithURL:[NSURL URLWithString:_infoicon]];
        textview.textuname.text =_infouname;
        textview.likecount.text = _infolikecount;
        textview.commmentcout.text =  _infocommmentcout;
        textview.textcontent.text = _infocontent;
        textview.texttime.text = _infotime;
        [textview.zanbtn addTarget:self action:@selector(zanAction:) forControlEvents:UIControlEventTouchUpInside];
        [textview.caibtn addTarget:self action:@selector(zanAction:) forControlEvents:UIControlEventTouchUpInside];
        [textview.sharebtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
        textview.contentView.backgroundColor = [UIColor whiteColor];
        CGFloat  f=  [self heightForString:_infocontent size:14];
        textview.contentView.frame = CGRectMake(0, 0, kWidth, f+130);
        UIView *view = textview.contentView;
        self.tableView.tableHeaderView = view;
        
    }
    else if ([_type isEqualToString:@"image"])
    {
        ThingsimageTableViewCell *imaview = [[[NSBundle mainBundle]loadNibNamed:@"ThingsimageTableViewCell" owner:nil options:nil] objectAtIndex:0];
        [imaview.imaicon sd_setImageWithURL:[NSURL URLWithString:_infoicon]];
        imaview.imauname.text =_infouname;
        imaview.likecout.text = _infolikecount;
        imaview.commmentcount.text =  _infocommmentcout;
        imaview.imacontent.text = _infocontent;
        imaview.imatime.text =_infotime;
        [imaview.imapic sd_setImageWithURL:[NSURL URLWithString:_infoima]];
        imaview.imapic.frame =CGRectMake(10, 80+[self heightForString:_infocontent size:14],_imaw, _imah);
         [imaview.zanbtn addTarget:self action:@selector(zanAction:) forControlEvents:UIControlEventTouchUpInside];
         [imaview.caibtn addTarget:self action:@selector(zanAction:) forControlEvents:UIControlEventTouchUpInside];
        [imaview.sharebtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
        imaview.contentView.backgroundColor = [UIColor whiteColor];
        CGFloat  f=  [self heightForString:_infocontent size:14];
        imaview.contentView.frame = CGRectMake(0, 0, kWidth, f+160+_imah);
        UIView *view = imaview.contentView;
        self.tableView.tableHeaderView = view;
    }
    else
    {
        ThingsvideoTableViewCell *videoview = [[[NSBundle mainBundle]loadNibNamed:@"ThingsvideoTableViewCell" owner:nil options:nil] objectAtIndex:0];
        [videoview.videoicon sd_setImageWithURL:[NSURL URLWithString:_infoicon]];
        videoview.videoTitle.text =_infouname;
        videoview.videolagu.text = _infolikecount;
        videoview.videocomment.text =  _infocommmentcout;
        videoview.videocontent.text = _infocontent;
        videoview.videotime.text =_infotime;
        [videoview.zanbtn addTarget:self action:@selector(zanAction:) forControlEvents:UIControlEventTouchUpInside];
        [videoview.caibtn addTarget:self action:@selector(zanAction:) forControlEvents:UIControlEventTouchUpInside];
        [videoview.sharebtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
        videoview.contentView.frame = CGRectMake(0, 0, kWidth-10, 370);
        UIView *view = videoview.contentView;
        self.tableView.tableHeaderView = view;
    
    }
    //上拉and下拉刷新
    
    // 下拉刷新数据
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^
    {
        // 下拉刷新数据 需要重新网络请求
        _page= 1;
        [_listarry removeAllObjects];
        [self requestDataWithType:@"list"];
    }];
    
    //上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^
    {
         _page = _page+1;
         //再次请求数据
         [self requestDataWithType:@"list"];
    }];

}
#pragma mark------------   设置区头高度 ---------------
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
#pragma mark------------ 自定义区头---------------
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    UIView *hotview=[[UIView alloc]init];
    UILabel *hotlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    hotlabel.text =@"热门评论";
    hotlabel.font =[UIFont fontWithName:nil size:13];
    [hotview addSubview:hotlabel];
    UIView *listview=[[UIView alloc]init];
    UIButton *newbutton =[UIButton buttonWithType:UIButtonTypeSystem];
    newbutton.frame =CGRectMake(0, 0, 80, 30);
    [newbutton setTitle:@"最新评论" forState:UIControlStateNormal];
    newbutton.titleLabel.font = [UIFont fontWithName:nil size:13];
    [newbutton addTarget:self action:@selector(looklatest:) forControlEvents:UIControlEventTouchUpInside];
    [listview addSubview:newbutton];
    UIButton *authorbtn =[UIButton buttonWithType:UIButtonTypeSystem];
    authorbtn.frame =CGRectMake(100, 0, 100, 30);
    [authorbtn setTitle:@"楼主评论" forState:UIControlStateNormal];
    authorbtn.titleLabel.font = [UIFont fontWithName:nil size:13];
    [authorbtn addTarget:self action:@selector(lookauthoronly:) forControlEvents:UIControlEventTouchUpInside];
    [listview addSubview:authorbtn];
    
    if (section==0&&_hotarry.count!=0)
    {
        return hotview;
    }
    else if (section ==1)
    {
        
        return listview ;
    }
    return nil;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
#pragma mark-----tableview分区下行数----
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return _hotarry.count;
    }else
    {
     
        return  _listarry.count;
    }
   
}
#pragma mark-----tableviewcell----
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InfoTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"infocell" forIndexPath:indexPath];
   
    if (indexPath.section ==0)
    {
        ThingsListModel *model2 = _hotarry[indexPath.row];
        NSString *idstring2 = [NSString stringWithFormat:@"%@",model2.user.ID];
        NSString *substring2 = [idstring2 substringToIndex:idstring2.length/2];
        NSString *urlstring2 = [NSString stringWithFormat:@"%@/%@/medium/%@",substring2,idstring2,model2.user.icon];
        [cell.Infoicon sd_setImageWithURL:[NSURL URLWithString:[kiconurl stringByAppendingString:urlstring2]]];
        cell.Infouname.text = model2.user.login;
        cell.Infocontent.text = model2.content;
          return cell;
    }
     ThingsListModel *model = _listarry[indexPath.row];
    NSString *idstring = [NSString stringWithFormat:@"%@",model.user.ID];
    NSString *substring = [idstring substringToIndex:idstring.length/2];
    NSString *urlstring = [NSString stringWithFormat:@"%@/%@/medium/%@",substring,idstring,model.user.icon];
    [cell.Infoicon sd_setImageWithURL:[NSURL URLWithString:[kiconurl stringByAppendingString:urlstring]]];
    cell.Infouname.text = model.user.login;
    cell.Infocontent.text = model.content;
       return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section ==0)
    {
        ThingsListModel *model2 = _hotarry[indexPath.row];
        CGFloat  f=  [self heightForString:model2.content size:12];
        return f+75;
    }
    ThingsListModel *model = _listarry[indexPath.row];
    CGFloat  f=  [self heightForString:model.content size:12];
    return f+75;

}
- (CGFloat)heightForString:(NSString *)aString size:(NSInteger)size{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};
    CGRect rect = [aString boundingRectWithSize:CGSizeMake(300, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}
-(void)lookauthoronly:(UIButton *)sender
{
    [_listarry removeAllObjects];
    [self requestDataWithType:@"author"];
}
-(void)looklatest:(UIButton *)sender
{
    [_listarry removeAllObjects];
    [self requestDataWithType:@"list"];
}
#pragma mark-----网络请求----
- (void)requestDataWithType:(NSString *)type{
    if ([type isEqualToString:@"hot"])
    {
        [RequestManager initWithUrlString:_hotString requestType:@"GET" parDic:nil finishBlock:^(NSData *data)
         {
             NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
             NSArray *listArray = dataDic[@"items"];
             
             for (NSDictionary *dic in listArray)
             {
                 ThingsListModel *model =[[ThingsListModel alloc]init];
                 [model setValuesForKeysWithDictionary:dic];
                 [_hotarry  addObject:model];
             }
             dispatch_async(dispatch_get_main_queue(), ^
             {
                  [self.tableView reloadData];
                                
             });

             NSLog(@"热门评论请求成功");
             
         } errorBlock:^(NSError *error)
         {
             NSLog(@"热门评论请求失败");
         }];
        
    }
    else if([type isEqualToString:@"list"])
    {
        [RequestManager initWithUrlString:[NSString stringWithFormat:@"%@?page=%ld",_listString,(long)_page] requestType:@"GET" parDic:nil finishBlock:^(NSData *data)
         {
             NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
             NSArray *listArray = dataDic[@"items"];
             
             for (NSDictionary *dic in listArray)
             {
                 ThingsListModel *model =[[ThingsListModel alloc]init];
                 [model setValuesForKeysWithDictionary:dic];
                 [_listarry  addObject:model];
             }
             dispatch_async(dispatch_get_main_queue(), ^
            {
                [self.tableView reloadData];
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            });

             NSLog(@"最新评论请求成功");
             
         } errorBlock:^(NSError *error)
         {
             NSLog(@"最新评论请求失败");
         }];
    }
    else
    {
       [RequestManager initWithUrlString:_auhorString requestType:@"GET" parDic:nil finishBlock:^(NSData *data)
       {
           NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
           
           NSArray *listArray = dataDic[@"items"];
           
           for (NSDictionary *dic in listArray)
           {
               ThingsListModel *model =[[ThingsListModel alloc]init];
               [model setValuesForKeysWithDictionary:dic];
               [_listarry  addObject:model];
           }
           dispatch_async(dispatch_get_main_queue(), ^
            {
                [self.tableView reloadData];
                              
            });

           NSLog(@"楼主请求成功");
           
       } errorBlock:^(NSError *error)
       {
           NSLog(@"楼主请求失败");
       }];
    
    }
    
}
- (VideoPlayer *)player {
    if (!_player) {
        ThingsvideoTableViewCell *videoview = [[[NSBundle mainBundle]loadNibNamed:@"ThingsvideoTableViewCell" owner:nil options:nil] objectAtIndex:0];
        _player = [[VideoPlayer alloc] init];
        _player.frame = videoview.videoImageView.frame;
    }
    return _player;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if ([_type isEqualToString:@"video"])
    {
        self.player.videoUrl = self.mp4_url;
        [self.view addSubview:self.player];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if ([_type isEqualToString:@"video"])
    {
        [self.player destroyPlayer];
        self.player = nil;
    }
 
}
- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}


- (void)showAlert:(NSString *) _message{//时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:nil message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}
-(void)zanAction:(UIButton *)sender
{
    
    [self showAlert:@"因某种原因尚不能实现"];
}
-(void)shareAction:(UIButton *)sender
{
    
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:_infocontent
                                     images:_infoima
                                        url:nil
                                      title:nil
                                       type:SSDKContentTypeAuto];
    //2、分享（可以弹出我们的分享菜单和编辑界面）
    [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   
                   switch (state) {
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                           message:[NSString stringWithFormat:@"%@",error]
                                                                          delegate:nil
                                                                 cancelButtonTitle:@"OK"
                                                                 otherButtonTitles:nil, nil];
                           [alert show];
                           break;
                       }
                       default:
                           break;
                   }
               }
     ];



}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}




@end
